package com.wangjiangwen.exceptions;

import cn.dev33.satoken.exception.NotLoginException;
import com.wangjiangwen.bean.R;
import com.wangjiangwen.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public R<Void> handler(BindException e) {
        return R.get(400, e.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(StrUtil.COMMA)));
    }

    @ExceptionHandler(value = NotLoginException.class)
    public R<Void> handler(NotLoginException e) {
        log.error("exception message", e);
        return R.get(401, "登录已过期");
    }

    @ExceptionHandler(value = Exception.class)
    public R<Void> handler(Exception e) {
        log.error("exception message", e);
        return R.fail(e.getMessage());
    }
}
